#include "widget.h"
#include "ui_widget.h"
#include <QTimer>
#include <QString>
#include <QDateTime>
#include <fstream>
#include <sstream>

using namespace std;

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    timeCnt(0),tomatoCnt(0),
    file_name("tomato.log"),
    work_flag(true),
    logView(new Dialog(this)),
    ui(new Ui::Widget)
{
    ui->setupUi(this);
    ui->stopButton->setDisabled(true);

    timer = new QTimer();
    connect(timer,SIGNAL(timeout()),this,SLOT(timeUpdate()));
    connect(this,SIGNAL(tomatoTimeOut(const QString &)),this,SLOT(writeLog(const QString &)));
}

Widget::~Widget()
{
    delete timer;
    delete logView;
    delete ui;
}

void Widget::timeUpdate()
{
    stringstream buff;
    if(work_flag)
    {
        if(++timeCnt>=work)
        {
            tomatoUpdate();
            timeCnt = 0;
            work_flag =false;
            ui->label->setText("还可以休息");
            buff << (free-timeCnt)/60 << " : " << (free-timeCnt)%60 << flush;
            ui->timeLabel->setText(buff.str().c_str());
            return;
        }
        buff << (work-timeCnt)/60 << " : " << (work-timeCnt)%60 << flush;
    }
    else
    {
        if(++timeCnt>=free)
        {
            timer->stop();
            timeCnt = 0;
            work_flag =true;
            on_stopButton_clicked();
            ui->label->setText("剩余时间");
            return;
        }
        buff << (free-timeCnt)/60 << " : " << (free-timeCnt)%60 << flush;
    }

    ui->timeLabel->setText(buff.str().c_str());
}

void Widget::tomatoUpdate()
{
    ui->tomatoLabel->setText(QString::number(++tomatoCnt));
    QString log_line;
    log_line = ui->lineEdit->text() + "," + QDateTime::currentDateTime().toString();
    emit tomatoTimeOut(log_line);
}

void Widget::on_startButton_clicked()
{
    ui->startButton->setDisabled(true);
    ui->stopButton->setDisabled(false);
    timer->start(1000);
}

void Widget::on_stopButton_clicked()
{
    ui->startButton->setDisabled(false);
    ui->stopButton->setDisabled(true);
    timer->stop();
    timeCnt = 0;
    work_flag = true;
    ui->timeLabel->setText("0 : 0");
}

void Widget::writeLog(const QString &log_line)
{
    flog.open(file_name.c_str(), ios_base::app|ios_base::out|ios_base::in);
    flog<<log_line.toStdString()<<endl<<flush;
    flog.close();
}

void Widget::on_recordButton_clicked()
{
    char c;
    string text;
    ifstream fin(file_name.c_str());
    while(fin.get(c))
    {
        text.push_back(c);
    }
    fin.close();

    logView->setText(QString::fromUtf8(text.c_str()));
    logView->show();
}
